from django.http import JsonResponse
from django.template import Context, Template
from django.conf import settings
from django.shortcuts import redirect

from .models import Feed, Recipe
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import os


@login_required(login_url='/login')
def get_available_accessible_feeds(request):
    avail_pub_feed = Feed.objects.all().filter(available=True, public=True)
    # current_user_feed = Feed.objects.all().filter(user)
    return JsonResponse(avail_pub_feed)


@login_required(login_url='/login')
def save_new_rss_feed(request):
    newfeed = Feed()
    newfeed.title = request.POST['rss-title']
    newfeed.url = request.POST['rss-url']
    newfeed.type = 'r'
    newfeed.available = True
    newfeed.user = request.user
    newfeed.save()
    return redirect('/feed')


'''
data:
{
    oldest_day: 7 #
    max_article: 50
    title: My NewFeed
    feeds: [{
        "title": "RSS TITLE",
        "url": "http://rssurl"
    },{
        "title": "RSS TITLE2",
        "url": "http://rssurl2"
    }]
}
'''
def make_recipe_from_rss(data):
    tmpl = ''
    with open(os.path.join(settings.BASE_DIR,'feed','templates','rssfeedrecipe.template'), 'r') as f:
        tmpl = f.read()

    recipe = Template(tmpl)
    context = Context(data)

    return recipe.render(context)
